#!/bin/bash
#
# 07/29/2012 - created

# hostname for Cassandra nodes
CASSANDRA_DIR=/usr/local/cassandra
CASSANDRA_HOSTS="$@"
CASSANDRA_NODES="$#"
HOSTS=""
NUM=1


function showBar {
 percDone=$(echo 'scale=2;'$1/$2*100 | bc)
 barLen=$(echo ${percDone%'.00'})
 bar=''
 fills=''
 for (( b=0; b<$barLen; b++ ))
 do
  bar=$bar"="
 done
 blankSpaces=$(echo $((100-$barLen)))
 for (( f=0; f<$blankSpaces; f++ ))
 do
  fills=$fills"."
 done
 echo -ne '['$bar'>'$fills']: '$barLen'%\r'
}


echo
gcutil addinstance --image=projects/google/images/centos-6-2-v20120621 --machine_type=n1-standard-1 --zone=us-central1-a ${CASSANDRA_HOSTS} 

echo
echo "Waiting for VMs creation to complete...."
for (( i=0; i<=9600; i++ ))
do
    showBar $i 9600
done
echo


# create cassandra.yaml files for each Cassandra node
for cs in ${CASSANDRA_HOSTS}
do
    hosts="$hosts,$cs"
done

hosts=`echo $hosts | tail -c +2`
echo $hosts

cp cassandra.yaml /tmp/
find /tmp/ -name cassandra.yaml -type f -exec sed -i -e "s/IP1, IP2, IP3/${hosts}/g" {} \;

tokens=`python castokgen.py ${CASSANDRA_NODES}`

echo $tokens

num=${NUM}

for cs in ${CASSANDRA_HOSTS}
do
    echo "counter is: $num"

    token=`echo $tokens | cut -f"${num}" -d" "`

    echo "current token is: ${token}"

    cp /tmp/cassandra.yaml /tmp/cassandra.yaml.${cs}

    find /tmp/ -name cassandra.yaml.${cs} -type f -exec sed -i -e "s/<Provide Token>/${token}/g" {} \;

   : $(( num++ ))
done



for cs in ${CASSANDRA_HOSTS}
do
     # copy the installation files
     gcutil push $cs apache-cassandra-1.0.7-bin.tar.gz getcass.sh bashrc.cassandra /tmp/cassandra.yaml.${cs} cassandra /tmp/

     # run the installation scrit
     gcutil ssh ${cs} /tmp/getcass.sh ${cs}

     # clean up the installation scripts
     #gcutil ssh ${cs} rm -f /tmp/apache-cassandra-1.0.7-bin.tar.gz /tmp/getcass.sh /tmp/bashrc.cassandra /tmp/cassandra.yaml.${cs}

     # report Cassandra status on this node
     gcutil ssh ${cs} "sudo -u root /etc/init.d/cassandra status"

     # report Cassandra ring status
     echo
     echo "Cassandra ring status...."
     gcutil ssh ${cs} "${CASSANDRA_DIR}/apache-cassandra-1.0.7/bin/nodetool -h cs1 -p 8080 ring"
     echo
done


# clean up local file system
rm -f /tmp/cassandra.yaml*

exit
